<style lang="less">
@import "./style.less";
</style>

<template>
    <div class="examReport">
        <el-tabs type="border-card"
                 v-model="activeTab">
            <!-- 学员报告 -->
            <el-tab-pane label="学员报告"
                         name="trainee">
                <div class="op-header">
                    <div class="search">
                        <el-cascader :options="enableOptions"
                                     :props="cascaderProps"
                                     class="enable-select"
                                     placeholder="启用状态"
                                     v-model="enableValue" />
                        <el-select :remote-method="value => searchTrainee(value, 'trainee')"
                                   class="search-input"
                                   filterable
                                   multiple
                                   placeholder="指定学员"
                                   remote
                                   size="small"
                                   v-model="selectedTrainee">
                            <el-option :key="item.userId"
                                       :label="item.name"
                                       :value="item.userId"
                                       v-for="item in trainees" />
                        </el-select>
                        <el-select :remote-method="value => searchTask(value, 'trainee')"
                                   class="search-input"
                                   filterable
                                   multiple
                                   placeholder="指定任务"
                                   remote
                                   size="small"
                                   v-model="selectedTask">
                            <el-option :key="item.id"
                                       :label="item.name"
                                       :value="item.id"
                                       v-for="item in examList.content" />
                        </el-select>
                        <el-cascader :clearable="true"
                                     :options="organizations"
                                     :props="cascaderProps"
                                     :show-all-levels="false"
                                     change-on-select
                                     class="department-select"
                                     placeholder="所属部门"
                                     v-model="departmentValue" />
                        <el-input class="search-input"
                                  placeholder="请输入查询关键字"
                                  prefix-icon="el-icon-search"
                                  size="small"
                                  v-model="searchInput" />
                        <el-button @click="search('trainee')"
                                   class="search-button"
                                   size="small"
                                   type="primary">
                            <i class="el-icon-search icon-right" />查询
                        </el-button>
                        <el-button @click="download('trainee')"
                                   class="search-button"
                                   size="small"
                                   type="primary">报告下载</el-button>
                        <el-button :disabled="!selectedRows.length"
                                   @click="deleteReport('trainee')"
                                   class="search-button"
                                   size="small"
                                   type="warning">清除报告</el-button>
                    </div>
                </div>
                <table-ex :columns="columns"
                          :on-operation="onClickOperation"
                          :on-page-change="onPageChange"
                          :on-select-change="rows => selectChange(rows, 'trainee')"
                          :rows="examReports"
                          :total="examReportsTotal" />
                <table-ex :columns="traineeExcelColumns"
                          :rows="traineeExcelData"
                          ref="table"
                          table-id="examReport"
                          v-show="false" />
                <!-- 组织报告 -->
            </el-tab-pane>
            <el-tab-pane label="组织报告"
                         name="organization">
                <div class="op-header">
                    <div class="search">
                        <el-cascader :clearable="true"
                                     :options="organizations"
                                     :props="cascaderProps"
                                     class="department-select"
                                     placeholder="所属部门"
                                     v-model="oDepartmentValue" />
                        <el-input class="search-input"
                                  placeholder="请输入查询关键字"
                                  prefix-icon="el-icon-search"
                                  size="small"
                                  v-model="searchInput" />
                        <el-button @click="search('organization')"
                                   class="search-button"
                                   size="small"
                                   type="primary">
                            <i class="el-icon-search icon-right" />查询
                        </el-button>
                        <el-button @click="download('organization')"
                                   class="search-button"
                                   size="small"
                                   type="primary">报告下载</el-button>
                    </div>
                </div>
                <table-ex :columns="oColumns"
                          :on-operation="onClickOperation"
                          :on-page-change="onEPageChange"
                          :rows="eOrganizationReports"
                          :total="eOrganizationTotal"
                          ref="eTable"
                          selection="none"
                          table-id="organizationReport" />
            </el-tab-pane>

            <!-- 数字录入 -->
            <el-tab-pane label="数字录入"
                         name="numberExam">
                <div class="op-header">
                    <div class="search">
                        <el-select class="search-input"
                                   placeholder="任务名称"
                                   size="small"
                                   :remote-method="value => searchTask(value, 'numberExam')"
                                   v-model="digitalFilter.paperName">
                            <el-option :value="null"
                                       label="无" />
                            <el-option :key="item.id"
                                       :label="item.name"
                                       :value="item.name"
                                       v-for="item in examList.content" />
                        </el-select>
                        <el-input class="search-input"
                                  placeholder="工号"
                                  prefix-icon="el-icon-search"
                                  size="small"
                                  v-model="digitalFilter.employeeNumber" />
                        <el-input class="search-input"
                                  placeholder="用户名"
                                  prefix-icon="el-icon-search"
                                  size="small"
                                  v-model="digitalFilter.userName" />
                        <el-input class="search-input"
                                  placeholder="机构名称"
                                  prefix-icon="el-icon-search"
                                  size="small"
                                  v-model="digitalFilter.orgName" />
                        <el-button @click="digital_search()"
                                   class="search-button"
                                   size="small"
                                   type="primary">
                            <i class="el-icon-search icon-right" />查询
                        </el-button>
                        <el-button @click="digital_down()"
                                   size="small"
                                   type="primary">报告下载</el-button>
                    </div>
                </div>
                <table-ex :columns="digitalInput"
                          :on-page-change="onEPageChangeNum"
                          :rows="numberExamTasks"
                          :total="numberPage"
                          ref="numberExam"
                          selection="none"
                          table-id="organizationReport" />
            </el-tab-pane>
            <!-- 传票翻打 -->
            <el-tab-pane label="传票翻打"
                         name="catationExam">
                <div class="op-header">
                    <div class="op-header">
                        <div class="search">
                            <el-select class="search-input"
                                       placeholder="任务名称"
                                       size="small"
                                       v-model="citationFilter.paperName">
                                <el-option :value="null"
                                           label="无" />
                                <el-option :key="item.id"
                                           :label="item.name"
                                           :value="item.name"
                                           v-for="item in examList.content" />
                            </el-select>
                            <el-input class="search-input"
                                      placeholder="工号"
                                      prefix-icon="el-icon-search"
                                      size="small"
                                      v-model="citationFilter.employeeNumber" />
                            <el-input class="search-input"
                                      placeholder="用户名"
                                      prefix-icon="el-icon-search"
                                      size="small"
                                      v-model="citationFilter.userName" />
                            <el-input class="search-input"
                                      placeholder="机构名称"
                                      prefix-icon="el-icon-search"
                                      size="small"
                                      v-model="citationFilter.orgName" />
                            <el-button @click="citation_search()"
                                       class="search-button"
                                       size="small"
                                       type="primary">
                                <i class="el-icon-search icon-right" />查询
                            </el-button>
                            <el-button @click="citation_down()"
                                       size="small"
                                       type="primary">报告下载</el-button>
                        </div>
                    </div>
                </div>
                <table-ex :columns="digitalInput"
                          :on-operation="onClickOperation"
                          :on-page-change="onEPageChangecitation"
                          :rows="citationExamTasks"
                          :total="citationPage"
                          ref="catationExam"
                          selection="none"
                          table-id="organizationReport" />
            </el-tab-pane>
        </el-tabs>
        <el-dialog :visible.sync="taskVisible"
                   title="查看任务">
            <div class="dialog-content">
                <table-ex :columns="taskColumns"
                          :on-operation="taskClickOperation"
                          :on-page-change="onTaskPageChange"
                          :rows="examReportTasks"
                          :total="eTaskTotal"
                          selection="none" />
            </div>
        </el-dialog>
        <el-dialog :visible.sync="detailVisible"
                   title="学习详情">
            <table-ex :columns="detailColumns"
                      :on-operation="onClickOperation"
                      :rows="detailRows"
                      isFooter
                      selection="none" />
        </el-dialog>
        <!-- score record -->
        <!-- 考试结果 -->
        <exam-result
                :results="examScoreDetails"
                :reviewResults="true"
                @close="scoreShow = false"
                mode="study"
                v-if="scoreShow"
        />
    </div>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex'
import examResult from '@/pages/course/components/examResult'
import pageConfig from './config'
import api from '@/api/index'
import tableEx from '@/components/table/tableEx'

export default {
  name: 'examReport',
  components: {
    'table-ex': tableEx,
    'exam-result': examResult
  },
  data() {
    return {
      // 学员报告
      enableValue: [],
      departmentValue: [],
      traineeInput: '',
      searchInput: '',
      columns: pageConfig.columns,
      // 组织报告
      oDepartmentValue: [],
      oSearchInput: '',
      oColumns: pageConfig.oColumns,
      digitalInput: pageConfig.digitalInput,
      // 公共数据
      scoreShow: false,
      examScoreDetails: null,
      taskVisible: false,
      detailVisible: false,
      currentTaskType: '',
      taskRows: [],
      taskColumns: pageConfig.taskColumns,
      detailRows: [],
      detailColumns: pageConfig.detailColumns,
      activeTab: 'trainee',
      enableOptions: pageConfig.enableOptions,
      cascaderProps: {
        value: 'id',
        label: 'title',
        children: 'children'
      },
      // table条目选择
      selectedRows: [],
      // 选择学员
      selectedTrainee: [],
      // 选择部门
      selectedTask: [],
      // 导出excel的columns
      traineeExcelColumns: pageConfig.traineeExcelColumns,
      // 导出excel的数据
      traineeExcelData: [],
      // 工号
      digitalFilter: {
        employeeNumber: '',
        //用户名
        userName: '',
        // 机构名
        orgName: '',
        // 任务名称
        paperName: ''
      },
      citationFilter: {
        employeeNumber: '',
        //用户名
        userName: '',
        // 机构名
        orgName: '',
        // 任务名称
        paperName: ''
      }
    }
  },
  /**
   * 生命钩子
   **/
  created() {},
  mounted() {
    this.loadData()
  },
  /**
   * 计算
   **/
  computed: {
    ...mapGetters([
      'examReports',
      'eOrganizationReports',
      'organizations',
      'examReportTasks',
      'examReportsTotal',
      'eOrganizationTotal',
      'eTaskTotal',
      'numberPage',
      'citationPage',
      'trainees',
      'examList',
      'digitalExamData',
      'numberExamTasks',
      'citationExamTasks'
    ])
  },
  watch: {
     activeTab() {
         console.log("activeTab >> ", this.activeTab)
         this.searchTask(null, this.activeTab)
     }
  },
  /**
   * 事件
   **/
  methods: {
    ...mapActions([
      'getOrganizations',
      'getExamReports',
      'getEOrganizationReports',
      'getExamReport',
      'getEOrganizationReport',
      'getTrainees',
      'deleteEmployeeExamReport',
      'getexamlist',
      'obtainExamResult',
      'againNumberExam',
      'againcitationExam'
    ]),

    ...mapMutations([
      'SETEXAMREPORTSPAGE',
      'SETEORGANIZATIONPAGE',
      'SETETASKPAGE',
      'SETDIGITALDATA',
      'SETEXAMNUMBERLIST',
      'SETEXAMNUMBERLISTPAGE',
      'SETEXCITATIONPAGE'
    ]),

    loadData() {
      this.getExamReports()
      this.getOrganizations()
      this.getEOrganizationReports()
      this.getTrainees()
      this.searchTask(null, 'trainee')
      this.againNumberExam()
      this.againcitationExam()
    },
    search(type) {
      if (type === 'trainee') {
        const filter = {
          taskKeyword: this.searchInput ? this.searchInput : null,
          organizationId: this.departmentValue
            ? this.departmentValue[this.departmentValue.length - 1]
            : null,
          taskEnabled: this.enableValue[0] ? this.enableValue[0] : null,
          employeeIds: this.selectedTrainee,
          taskIds: this.selectedTask
        }
        this.SETEXAMREPORTSPAGE({
          number: 1,
          filter
        })
        this.getExamReports()
      } else {
        const filter = {
          title: this.oSearchInput ? this.oSearchInput : null,
          organizationId: this.oDepartmentValue
            ? this.oDepartmentValue[this.oDepartmentValue.length - 1]
            : null
        }
        this.SETEORGANIZATIONPAGE({
          number: 1,
          filter
        })
        this.getEOrganizationReports()
      }
    },
    // 导出Excel
    download(type) {
      if (type === 'trainee') {
        let filter = {
          size: 1000,
          number: 0,
          total: 0,
          pages: 1,
          filter: {
            taskIds: this.selectedTask
          }
        }
        api.getExamReports({
          method: 'post',
          data: filter,
          success: res => {
            // 字段处理
            if (res.content && res.content.length) {
              for (let item of res.content) {
                item.user = item.trainee.username
                item.name = item.trainee.name
                item.numberId = item.trainee.employeeId
                item.jobTitle = item.trainee.jobTitle
                if (item.trainee.organizationTitles) {
                  item.institution = item.trainee.organizationTitles.join('/')
                }
                item.taskFinishedPercent =
                  item.businessCountOfAssigned === 0
                    ? 0
                    : (item.businessCountOfFinished /
                        item.businessCountOfAssigned) *
                        100 +
                      '%'
                item.businessPassedPercent =
                  item.businessCountOfAssigned === 0
                    ? 0
                    : (item.businessCountOfPassed /
                        item.businessCountOfAssigned) *
                        100 +
                      '%'
              }
            }
            this.traineeExcelData = res.content
            setTimeout(() => {
              console.log(this.$refs.table)
              this.$refs.table.exportExcel()
            }, 500)
          }
        })
      } else if (type === 'numberExam') {
        this.$refs.numberExam.exportExcel()
      } else if (type === 'catationExam') {
        this.$refs.catationExam.exportExcel()
      } else {
        this.$refs.eTable.exportExcel()
      }
    },
    // 清除报告
    deleteReport(type) {
      let lIds = this.selectedRows.map(item => {
        return item.trainee.employeeId
      })
      this.deleteEmployeeExamReport({ lIds })
    },
    // 选择条目
    selectChange(rows, type) {
      this.selectedRows = rows
    },
    // 搜索员工
    searchTrainee(value, type) {
      let filter = {
        size: 100,
        number: 0,
        pages: 0,
        filter: {
          enabled: null,
          name: value
        }
      }
      this.getTrainees(filter)
    },
    searchTask(value, type) {
      let practiceTypes = []
      if(type === 'trainee') {
          practiceTypes = ['business']
      } else if(type === 'numberExam') {
          practiceTypes = ['number']
      } else if(type === 'catationExam') {
          practiceTypes = ['citation', 'citation_fixed']
      }
      let filter = {
        size: 500,
        number: 0,
        pages: 0,
        filter: {
          enabled: null,
          name: value,
          practiceTypes
        }
      }
      this.getexamlist(filter)
    },
    onClickOperation(oper, row) {
      this.taskRows = []
      if (oper.prop === 'edit') {
        this.currentTaskType = 't'
        this.taskColumns = pageConfig.taskColumns
        let filter = {
          employeeIds: [row.trainee.userId]
        }
        this.$store.commit('SETETASKPAGE', { number: 1, filter })
        this.getExamReport()
      } else if(oper.prop === 'scoreDetail') {
        this.scoreShow = true
        this.examScoreDetails = row.lastRecord && row.lastRecord.examStepsContent ? JSON.parse(row.lastRecord.examStepsContent) : {}
        console.log("scoreDetail >> ", row, this.examReportTasks)
      } else {
        this.currentTaskType = 'o'
        this.taskColumns = pageConfig.oTaskColumns
        let filter = {
          organizationId: row.organization.id
        }
        this.$store.commit('SETETASKPAGE', { number: 1, filter })
        this.getEOrganizationReport()
      }
      this.taskVisible = true
    },

    taskClickOperation(prop, row) {
      this.detailRows = []
      if (row.businessRecords && row.businessRecords.length) {
        row.businessRecords.forEach(item => {
          Object.assign(item, item.lastRecord)
          item.name = item.business.name
          if (item.timeCost < 0) {
            item.timeCost = 'N/A'
          }
        })
        this.detailRows = row.businessRecords
      }
      this.detailVisible = true
    },

    onPageChange(number) {
      this.SETEXAMREPORTSPAGE({ number })
      this.getExamReports()
    },
    onEPageChange(number) {
      this.SETEORGANIZATIONPAGE({ number })
      this.getEOrganizationReports()
    },
    // 传票翻打
    citation_search() {
      let filter = {
        ...this.citationFilter
      }
      this.SETEXCITATIONPAGE({ number: 1, filter })
      this.againcitationExam()
    },
    onEPageChangecitation(number) {
      this.SETEXCITATIONPAGE({ number })
      this.againcitationExam()
    },
    citation_down() {
      var query = `?name=citation&type=exam&employeeNumber=${
        this.citationFilter.employeeNumber
      }&userName=${this.citationFilter.userName}&orgName=${
        this.citationFilter.orgName
      }&paperName=${this.citationFilter.paperName}`
      window.location.href = `/api/digital/typing_result/csv${query}`
    },
    // 数字录入
    digital_search() {
      let filter = {
        ...this.digitalFilter
      }
      this.SETEXAMNUMBERLISTPAGE({ number: 1, filter })
      this.againNumberExam()
    },
    onEPageChangeNum(number) {
      this.SETEXAMNUMBERLISTPAGE({ number })
      this.againNumberExam()
    },
    digital_down() {
      var query = `?name=number&type=exam&employeeNumber=${
        this.digitalFilter.employeeNumber
      }&userName=${this.digitalFilter.userName}&orgName=${
        this.digitalFilter.orgName
      }&paperName=${this.digitalFilter.paperName}`
      window.location.href = `/api/digital/typing_result/csv${query}`
    },
    onTaskPageChange(number) {
      this.SETETASKPAGE({ number })
      if (this.currentTaskType === 't') {
        this.getExamReport()
      } else {
        this.getEOrganizationReport()
      }
    }
  }
}
</script>

